package es.udc.emarketapp.emarket.model.purchase.purchaseFacade.actions;

import es.udc.emarketapp.emarket.model.orderDetails.dao.SQLOrderDetailsDAO;
import es.udc.emarketapp.emarket.model.orderDetails.dao.SQLOrderDetailsDAOFactory;
import es.udc.emarketapp.emarket.model.orderDetails.vo.OrderDetailsVO;
import es.udc.emarketapp.emarket.model.purchase.purchaseFacade.vo.OrderDetailsChunkVO;


import java.sql.Connection;
import java.util.List;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.NonTransactionalPlainAction;

public class FindOrderDetailsByPurchaseAction implements NonTransactionalPlainAction {

	private Long idPurchase;
	private int startIndex;
	private int count;

	public FindOrderDetailsByPurchaseAction(Long idPurchase, int startIndex, int count) {

		this.idPurchase = idPurchase;
		this.startIndex = startIndex;
		this.count = count;
	}

	/**
	 * 
	 * @return An instance of <code>OrderChunkVO</code> objects.
	 */
	public Object execute(Connection connection) throws InternalErrorException {

		/*
		 * Find count+1 purchases to determine if there exist more products
		 * above the specified range.
		 */
		SQLOrderDetailsDAO orderDAO = SQLOrderDetailsDAOFactory.getDAO();
		List<OrderDetailsVO> orderVOs = orderDAO.findByPurchase(connection,
				idPurchase, startIndex, count + 1);
		boolean existMoreOrders = orderVOs.size() == (count + 1);

		/*
		 * Remove the last account from the returned list if there exist more
		 * accounts above the specified range.
		 */
		if (existMoreOrders) {
			orderVOs.remove(orderVOs.size() - 1);
		}

		
		
		return new OrderDetailsChunkVO(orderVOs, existMoreOrders);

	}

}